package com.bishengdfc;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.text.DecimalFormat;

/**
 * Created by david on 2016-02-15.
 */
public class RFIDReaerActivity extends Activity {
    private TextView tv_label;
    private TextView promts;
    private NfcAdapter nfcAdapter;
    private Intent m_intent;
//    private Tag m_tagFromIntent;
    private byte[] b_nfcid = null;

//
//    private String mimaStr = "FFFFFFFFFFFF";

  /*  private Runnable readCallback = new Runnable() {
        @Override
        public void run() {
            read();
        }
    };
*/
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //ActivityTool.hideTitle(this);
       // ActivityTool.fullScreen(this);
        //ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.rfidreader_layout);
        SystemStatus.RFID_Code = "";
        tv_label = (TextView)findViewById(R.id.tv_label);
        promts=(TextView)findViewById(R.id.promt);
//        tv_label.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
////                if (onReadCompletedListener != null)
////                    onReadCompletedListener.onRead(this, "0012345678");
////                dialog.dismiss();
//                SystemStatus.RFID_Code = "0012345678";
//                setResult(1);
//                finish();
//            }
//        });
        try {
            nfcAdapter = NfcAdapter.getDefaultAdapter(this);
            if (nfcAdapter == null) {
                tv_label.setText("设备不支持NFC");
                // finish();
                return;
            }
            if (!nfcAdapter.isEnabled()) {
                tv_label.setText("请在系统设置中先启用NFC功能！");
                //finish();
                return;
            }
            processAdapterAction(getIntent());
        } catch (Exception e) {
            e.printStackTrace();
            tv_label.setText("设备不支持NFC");
        }
    }

    public void processAdapterAction(Intent intent)
    {
        //当系统检测到tag中含有NDEF格式的数据时，且系统中有activity声明可以接受包含NDEF数据的Intent的时候，系统会优先发出这个action的intent。
        //得到是否检测到ACTION_NDEF_DISCOVERED触发                           序号1
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
            System.out.println("ACTION_NDEF_DISCOVERED");
            //处理该intent
            processIntent(intent);
            return;
        }
        //当没有任何一个activity声明自己可以响应ACTION_NDEF_DISCOVERED时，系统会尝试发出TECH的intent.即便你的tag中所包含的数据是NDEF的，但是如果这个数据的MIME type或URI不能和任何一个activity所声明的想吻合，系统也一样会尝试发出tech格式的intent，而不是NDEF.
        //得到是否检测到ACTION_TECH_DISCOVERED触发                           序号2
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            System.out.println("ACTION_TECH_DISCOVERED");
            //处理该intent
            processIntent(intent);
            return;
        }
        //当系统发现前两个intent在系统中无人会接受的时候，就只好发这个默认的TAG类型的
        //得到是否检测到ACTION_TAG_DISCOVERED触发                           序号3
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            System.out.println("ACTION_TAG_DISCOVERED");
            //处理该intent
            processIntent(intent);
            return;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (nfcAdapter!=null) {
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
            IntentFilter[] ndef = new IntentFilter[]{new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)};
            String[][] mTechLists = new String[][]{
                    new String[]{NfcF.class.getName()},
                    new String[]{NfcA.class.getName()},
                    new String[]{NfcB.class.getName()},
                    new String[]{NfcV.class.getName()},
            };
            nfcAdapter.enableForegroundDispatch(this, pendingIntent, ndef, mTechLists);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (nfcAdapter!=null)
            nfcAdapter.disableForegroundDispatch(this);
    }

    @Override
    public void onNewIntent(Intent intent) {
        if (nfcAdapter!=null)
            processAdapterAction(intent);
    }

    //字符序列转换为16进制字符串
    private String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        char[] buffer = new char[2];
        for (int i = 0; i < src.length; i++) {
            buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);
            buffer[1] = Character.forDigit(src[i] & 0x0F, 16);
            System.out.println(buffer);
            stringBuilder.append(buffer);
        }
        return stringBuilder.toString();
    }

    private String byteArrayToIntString(byte[] b) {
        int i =  b[3] & 0xFF |
                (b[2] & 0xFF) << 8 |
                (b[1] & 0xFF) << 16 |
                (b[0] & 0xFF) << 24;
        return new DecimalFormat("0000000000").format(i);
    }

    private void processIntent(Intent intent) {
     /*   m_intent=intent;
        b_nfcid = m_intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);*/
       //取出封装在intent中的TAG
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        for (String tech : tagFromIntent.getTechList()) {
            System.out.println(tech);
        }
        boolean auth = false;
        //读取TAG
        MifareClassic mfc = MifareClassic.get(tagFromIntent);
        try {
            String metaInfo = "";
            //Enable I/O operations to the tag from this TagTechnology object.
            mfc.connect();
            int type = mfc.getType();//获取TAG的类型
            int sectorCount = mfc.getSectorCount();//获取TAG中包含的扇区数
            String typeS = "";
            switch (type) {
                case MifareClassic.TYPE_CLASSIC:
                    typeS = "TYPE_CLASSIC";
                    break;
                case MifareClassic.TYPE_PLUS:
                    typeS = "TYPE_PLUS";
                    break;
                case MifareClassic.TYPE_PRO:
                    typeS = "TYPE_PRO";
                    break;
                case MifareClassic.TYPE_UNKNOWN:
                    typeS = "TYPE_UNKNOWN";
                    break;
            }
           // metaInfo += "卡片类型：" + typeS + "\n共" + sectorCount + "个扇区\n共"+ mfc.getBlockCount() + "个块\n存储空间: " + mfc.getSize() + "B\n";

           //  for (int j = 0; j < sectorCount; j++) {
                //Authenticate a sector with key A.
            int j=0;
                auth = mfc.authenticateSectorWithKeyA(j,
                        MifareClassic.KEY_DEFAULT);
                int bCount;
                int bIndex;
                if (auth) {
                   // metaInfo += "扇区 " + j + ":验证成功\n";
                    // 读取扇区中的块
                    bCount = mfc.getBlockCountInSector(j);
                    bIndex = mfc.sectorToBlock(j);
                    bIndex=1;
                   // for (int i = 0; i < bCount; i++) {
                        byte[] data = mfc.readBlock(bIndex);
                        //metaInfo += "块 " + bIndex + " : "+ bytesToHexString(data) + "\n";

                    metaInfo += "" + bytesToHexString(data) + "";

                     //   bIndex++;
                  //  }
                } else {
                    metaInfo += "Sector " + j + ":验证失败\n";
                }



           // byteArrayToIntString(data);
       //     }



           /* for (int j = 0; j < sectorCount; j++) {
                //Authenticate a sector with key A.
                auth = mfc.authenticateSectorWithKeyA(j,
                        MifareClassic.KEY_DEFAULT);
                int bCount;
                int bIndex;
                if (auth) {
                    metaInfo += "Sector " + j + ":验证成功\n";
                    // 读取扇区中的块
                    bCount = mfc.getBlockCountInSector(j);
                    bIndex = mfc.sectorToBlock(j);
                    for (int i = 0; i < bCount; i++) {
                        byte[] data = mfc.readBlock(bIndex);
                        metaInfo += "Block " + bIndex + " : "
                                + bytesToHexString(data) + "\n";
                        bIndex++;
                    }
                } else {
                    metaInfo += "Sector " + j + ":验证失败\n";
                }
            }*/

            Log.i("===取出的值是===",""+metaInfo+"");

           //String.substring(metaInfo,1,3);
            Log.i("===截取之后的metaInfo===",""+metaInfo.substring(14,metaInfo.length())+"");//截取之后的

            promts.setText(metaInfo);
            //Toast.makeText(this,metaInfo,Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

        //取出封装在intent中的TAG
//        m_tagFromIntent= intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        //System.out.print(m_tagFromIntent);
  //      RFIDReaerActivity.this.runOnUiThread(readCallback);
  //  }

/*    private void read() {
        try {
//            String metaInfo = "";
            SystemStatus.RFID_Code = bytesToHexString(b_nfcid).toUpperCase();
//            metaInfo += "<UID>D:"+ SystemStatus.RFID_Code + "\n";
//            metaInfo += "<UID>H:"+ byteArrayToIntString(b_nfcid) + "\n";
            Toast.makeText(this, SystemStatus.RFID_Code, Toast.LENGTH_LONG).show();
            //setResult(1);
           // finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}
